package world.liquor.controller;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import world.liquor.domain.BeerAssessment;
import world.liquor.service.BeerAssessmentService;

@Controller
public class BeerAssessmentController {
	
	private BeerAssessmentService service;
	@Autowired
	public BeerAssessmentController(BeerAssessmentService service){
		this.service = service;
	}
	
	
	/**
	 * 특정 회원이 맥주를 평가한 평가정보를 등록
	 * @param memberId (회원 ID)
	 * @param beerInfoId (맥주 ID)
	 * @param grade (평가점수)
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping("/liquor/register_myBeer.do")
	public String registerBeerAssessment(String memberId, String beerInfoId, int grade, ModelMap map) throws SQLException{
		BeerAssessment result = null;
		
		//회원의 ID와 맥주ID로 평가한 정보가 있는지 조회
		BeerAssessment assChk = service.selectAssessmentByMemberAndBeerId(memberId, beerInfoId);
		
		//1. 이미 회원이 해당 맥주에 대한 평가를 등록한 상태이면, 새로 평가한 평가점수(grade)로 업데이트
		if(assChk != null){
			BeerAssessment assUpdate = new BeerAssessment(assChk.getBeerAssessmentId(), memberId, beerInfoId, grade);
			service.updateAssessment(assUpdate);
			result = assUpdate;		
		//2. 회원이 맥주에 대한 평가를 새로 하는 경우, 평가점수 등록
		}else{
			BeerAssessment assess = new BeerAssessment(memberId, beerInfoId, grade);
			service.registerAssessment(assess);
			result = assess;
		}
		
		map.addAttribute("assess", result);	
		return "jsonView";
	}
	
	@RequestMapping("/liquor/delete_myBeer.do")
	public String deleteBeerAssessment(String memberId, String beerInfoId) throws SQLException{
		BeerAssessment assess = service.selectAssessmentByMemberAndBeerId(memberId, beerInfoId);
		int assessId = assess.getBeerAssessmentId();
		
		service.deleteAssessment(assessId);
		
		return "jsonView";
	}
	
	
	
	
	
	
}
